<template>
  <view class="patrol-management-page">
    <!-- 导航栏 -->
    <u-navbar title="巡逻管理" back-icon="arrow-left" />
    
    <!-- 筛选区域 -->
    <view class="filter-section">
      <view class="filter-row">
        <u-picker
          :show="showRoutePicker"
          :columns="routeColumns"
          @confirm="onRouteConfirm"
          @cancel="showRoutePicker = false"
          title="选择巡逻路线"
        />
        <u-input
          v-model="filterForm.routeName"
          placeholder="巡逻路线"
          readonly
          @click="showRoutePicker = true"
          class="filter-input"
        />
        <u-picker
          :show="showStatusPicker"
          :columns="statusColumns"
          @confirm="onStatusConfirm"
          @cancel="showStatusPicker = false"
          title="选择状态"
        />
        <u-input
          v-model="filterForm.statusText"
          placeholder="状态"
          readonly
          @click="showStatusPicker = true"
          class="filter-input"
        />
      </view>
      <view class="filter-row">
        <u-input
          v-model="filterForm.startDate"
          placeholder="开始日期"
          readonly
          @click="showStartDatePicker = true"
          class="filter-input"
        />
        <u-input
          v-model="filterForm.endDate"
          placeholder="结束日期"
          readonly
          @click="showEndDatePicker = true"
          class="filter-input"
        />
        <u-button 
          type="primary" 
          text="搜索" 
          size="mini"
          @click="handleSearch"
        />
      </view>
    </view>

    <!-- 列表区域 -->
    <scroll-view 
      scroll-y="true" 
      class="list-scroll" 
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view class="list-content">
        <!-- 巡逻列表 -->
        <view 
          v-for="item in patrolList" 
          :key="item.id"
          class="patrol-card"
          @click="goToPatrolDetail(item.id)"
        >
          <view class="card-header">
            <view class="header-left">
              <text class="route-name">{{ item.routeName }}</text>
              <u-tag 
                :text="getStatusText(item.status)" 
                :type="getStatusType(item.status)" 
                size="mini"
              />
            </view>
            <text class="patrol-date">{{ formatDate(item.patrolDate) }}</text>
          </view>
          
          <view class="card-content">
            <view class="content-item">
              <u-icon name="user" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">{{ item.userName || '未知用户' }}</text>
            </view>
            <view class="content-item">
              <u-icon name="clock" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">{{ formatTime(item.startTime) }} - {{ formatTime(item.endTime) }}</text>
            </view>
            <view class="content-item" v-if="item.checkpointsCompleted">
              <u-icon name="map-pin" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">已完成检查点：{{ getCompletedCheckpointsCount(item.checkpointsCompleted) }}个</text>
            </view>
            <view class="content-item" v-if="item.remark">
              <u-icon name="file-text" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">{{ item.remark }}</text>
            </view>
          </view>
          
          <view class="card-footer">
            <view class="duration-info">
              <text class="duration-text">{{ getDuration(item.startTime, item.endTime) }}</text>
            </view>
            
            <view class="action-buttons">
              <u-button 
                v-if="item.status === 1"
                type="success" 
                text="继续巡逻"
                size="mini"
                @click.stop="goToPatrolExecute(item.id)"
                class="action-btn"
              />
              <u-button 
                v-else
                type="info" 
                text="详情"
                size="mini"
                @click.stop="goToPatrolDetail(item.id)"
                class="action-btn"
              />
            </view>
          </view>
        </view>
        
        <!-- 空状态 -->
        <view v-if="patrolList.length === 0 && !loading" class="empty-state">
          <u-empty text="暂无巡逻记录" icon="shield" mode="list" />
        </view>
        
        <!-- 加载更多提示 -->
        <view v-if="patrolList.length > 0" class="load-more-tip">
          <text v-if="loading" class="tip-text">加载中...</text>
          <text v-else-if="hasMore" class="tip-text">上拉加载更多</text>
          <text v-else class="tip-text">没有更多数据了</text>
        </view>
      </view>
    </scroll-view>

    <!-- 开始巡逻按钮 -->
    <view class="start-patrol-button" @click="goToStartPatrol">
      <u-icon name="play-circle" color="#fff" size="24"></u-icon>
      <text class="button-text">开始巡逻</text>
    </view>

    <!-- 日期选择器 -->
    <u-datetime-picker
      :show="showStartDatePicker"
      v-model="startDateValue"
      mode="date"
      @confirm="onStartDateConfirm"
      @cancel="showStartDatePicker = false"
      title="选择开始日期"
    />
    
    <u-datetime-picker
      :show="showEndDatePicker"
      v-model="endDateValue"
      mode="date"
      @confirm="onEndDateConfirm"
      @cancel="showEndDatePicker = false"
      title="选择结束日期"
    />
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getSecurityPatrolPage, getSecurityRoutePage } from '@/api/security'

// 响应式数据
const patrolList = ref([])
const routeList = ref([])
const loading = ref(false)
const refreshing = ref(false)
const hasMore = ref(true)

// 分页数据
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 筛选表单
const filterForm = reactive({
  routeId: '',
  routeName: '',
  status: '',
  statusText: '',
  startDate: '',
  endDate: ''
})

// 选择器显示状态
const showRoutePicker = ref(false)
const showStatusPicker = ref(false)
const showStartDatePicker = ref(false)
const showEndDatePicker = ref(false)

// 日期值
const startDateValue = ref('')
const endDateValue = ref('')

// 选择器数据
const statusColumns = ref([[
  { label: '进行中', value: 1 },
  { label: '已完成', value: 2 },
  { label: '异常中断', value: 3 }
]])

const routeColumns = ref([[]])

// 页面加载时获取数据
onMounted(() => {
  loadRouteList()
  loadPatrolList()
})

/**
 * 加载路线列表
 */
const loadRouteList = async () => {
  try {
    const response = await getSecurityRoutePage({
      pageNum: 1,
      pageSize: 100,
      status: 1 // 只获取启用的路线
    })
    if (response.success && response.data) {
      routeList.value = response.data.records || []
      routeColumns.value = [[
        { label: '全部路线', value: '' },
        ...routeList.value.map(route => ({
          label: route.routeName,
          value: route.id
        }))
      ]]
    }
  } catch (error) {
    console.error('加载路线列表失败:', error)
  }
}

/**
 * 加载巡逻列表
 */
const loadPatrolList = async (isRefresh = false) => {
  try {
    if (isRefresh) {
      pagination.pageNum = 1
      patrolList.value = []
      hasMore.value = true
    }
    
    loading.value = true
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      routeId: filterForm.routeId,
      status: filterForm.status,
      startDate: filterForm.startDate,
      endDate: filterForm.endDate
    }
    
    const response = await getSecurityPatrolPage(params)
    if (response.success && response.data) {
      const { records, total } = response.data
      
      if (isRefresh) {
        patrolList.value = records || []
      } else {
        patrolList.value.push(...(records || []))
      }
      
      pagination.total = total || 0
      hasMore.value = patrolList.value.length < pagination.total
    }
  } catch (error) {
    console.error('加载巡逻列表失败:', error)
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none'
    })
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

/**
 * 搜索处理
 */
const handleSearch = () => {
  loadPatrolList(true)
}

/**
 * 路线选择确认
 */
const onRouteConfirm = (event) => {
  const selectedRoute = event.value[0]
  filterForm.routeId = selectedRoute.value
  filterForm.routeName = selectedRoute.label
  showRoutePicker.value = false
  loadPatrolList(true)
}

/**
 * 状态选择确认
 */
const onStatusConfirm = (event) => {
  const selectedStatus = event.value[0]
  filterForm.status = selectedStatus.value
  filterForm.statusText = selectedStatus.label
  showStatusPicker.value = false
  loadPatrolList(true)
}

/**
 * 开始日期确认
 */
const onStartDateConfirm = (event) => {
  filterForm.startDate = event.value
  showStartDatePicker.value = false
  loadPatrolList(true)
}

/**
 * 结束日期确认
 */
const onEndDateConfirm = (event) => {
  filterForm.endDate = event.value
  showEndDatePicker.value = false
  loadPatrolList(true)
}

/**
 * 下拉刷新
 */
const onRefresh = () => {
  refreshing.value = true
  loadPatrolList(true)
}

/**
 * 加载更多
 */
const loadMore = () => {
  if (!loading.value && hasMore.value) {
    pagination.pageNum++
    loadPatrolList()
  }
}

/**
 * 获取状态文本
 */
const getStatusText = (status) => {
  const statusMap = {
    1: '进行中',
    2: '已完成',
    3: '异常中断'
  }
  return statusMap[status] || '未知状态'
}

/**
 * 获取状态类型
 */
const getStatusType = (status) => {
  const typeMap = {
    1: 'primary',
    2: 'success',
    3: 'error'
  }
  return typeMap[status] || 'info'
}

/**
 * 获取已完成检查点数量
 */
const getCompletedCheckpointsCount = (checkpointsCompleted) => {
  if (!checkpointsCompleted) return 0
  try {
    const data = typeof checkpointsCompleted === 'string' ? JSON.parse(checkpointsCompleted) : checkpointsCompleted
    return Array.isArray(data) ? data.length : 0
  } catch (error) {
    return 0
  }
}

/**
 * 获取持续时间
 */
const getDuration = (startTime, endTime) => {
  if (!startTime) return '未开始'
  if (!endTime) return '进行中'
  
  const start = new Date(startTime)
  const end = new Date(endTime)
  const duration = Math.floor((end - start) / (1000 * 60)) // 分钟
  
  if (duration < 60) {
    return `${duration}分钟`
  } else {
    const hours = Math.floor(duration / 60)
    const minutes = duration % 60
    return `${hours}小时${minutes}分钟`
  }
}

/**
 * 格式化日期
 */
const formatDate = (date) => {
  if (!date) return ''
  const dateObj = new Date(date)
  return dateObj.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

/**
 * 格式化时间
 */
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 页面导航方法
const goToPatrolDetail = (id) => {
  uni.navigateTo({
    url: `/pages/property-work/security-management/patrol-detail?id=${id}`
  })
}

const goToPatrolExecute = (id) => {
  uni.navigateTo({
    url: `/pages/property-work/security-management/patrol-execute?id=${id}`
  })
}

const goToStartPatrol = () => {
  uni.navigateTo({
    url: '/pages/property-work/security-management/patrol-start'
  })
}
</script>

<style lang="scss" scoped>
.patrol-management-page {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.filter-section {
  background: white;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  .filter-row {
    display: flex;
    align-items: center;
    gap: 16rpx;
    margin-bottom: 16rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .filter-input {
      flex: 1;
    }
  }
}

.list-scroll {
  flex: 1;
  min-height: 0;
}

.list-content {
  padding: 20rpx;
}

.patrol-card {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 16rpx;
      
      .route-name {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
      }
    }
    
    .patrol-date {
      font-size: 24rpx;
      color: #999;
    }
  }
  
  .card-content {
    margin-bottom: 20rpx;
    
    .content-item {
      display: flex;
      align-items: center;
      gap: 12rpx;
      margin-bottom: 12rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .item-icon {
        flex-shrink: 0;
      }
      
      .item-text {
        font-size: 26rpx;
        color: #666;
        line-height: 1.4;
        word-break: break-all;
      }
    }
  }
  
  .card-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .duration-info {
      .duration-text {
        font-size: 24rpx;
        color: #666;
      }
    }
    
    .action-buttons {
      .action-btn {
        min-width: 120rpx;
      }
    }
  }
}

.empty-state {
  padding: 100rpx 0;
  text-align: center;
}

.load-more-tip {
  padding: 30rpx 0;
  text-align: center;
  
  .tip-text {
    font-size: 24rpx;
    color: #999;
  }
}

.start-patrol-button {
  position: fixed;
  bottom: 40rpx;
  right: 40rpx;
  background: linear-gradient(135deg, #2ed573 0%, #7bed9f 100%);
  border-radius: 50rpx;
  padding: 20rpx 30rpx;
  display: flex;
  align-items: center;
  gap: 12rpx;
  box-shadow: 0 4rpx 20rpx rgba(46, 213, 115, 0.4);
  z-index: 999;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.95);
  }
  
  .button-text {
    color: white;
    font-size: 28rpx;
    font-weight: 600;
  }
}
</style>
